package com.desay.pangoo.itmt.config;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.CommonResponse;
import com.desay.pangoo.common.lite.lang.web.CustomException;
import com.desay.pangoo.common.lite.lang.web.ResultCodeEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * @author uidq3374
 *         <p>
 *         全局错误处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * org.springframework.validation.annotation.Validated产生的exception
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public ResponseEntity<Object> handleException(MethodArgumentNotValidException ex) {
		log.error(ex.getMessage(), ex);
		StringBuilder msg = new StringBuilder();
		ex.getBindingResult().getAllErrors().forEach(error -> {
			msg.append(error.getDefaultMessage());
			msg.append(" \n");
		});
		return new ResponseEntity<>(CommonResponse.failure(ResultCodeEnum.PARAM_IS_INVALID, msg.toString()),
				HttpStatus.OK);
	}

	@ExceptionHandler(BusinessException.class)
	@ResponseBody
	public ResponseEntity<Object> handleException(BusinessException ex) {
		// 业务错误在可控范围内,不答应堆栈心细.
		log.warn(ex.getBusinessExceptionEnum().getMessage());
		return new ResponseEntity<>(CommonResponse.failure(ex.getBusinessExceptionEnum(), null), HttpStatus.OK);
	}

	/**
	 * 剩余的错误处理。
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseEntity<Object> handleException(Exception ex) {
		log.error(ex.getMessage(), ex);
		return new ResponseEntity<>(CommonResponse.failure(ResultCodeEnum.FAILURE, ex.getMessage()), HttpStatus.OK);
	}

	@ExceptionHandler(CustomException.class)
	public ResponseEntity<Object> handleException(CustomException e) {
		log.warn("code:{},msg:{}", e.getCode(), e.getMsg());
		return new ResponseEntity<>(new CommonResponse<>(e.getCode(), e.getMsg()), HttpStatus.OK);
	}
}